<template>
	<view>
		<view class="content">
			<scroll-view class="scroll-Y" scroll-y="true">
				<!-- 顶部收入统计区域 手机服务端 -->
				<view v-if="roleProperty==2" class="header">
					<view class="total-income">
						<text class="title">{{ $t('business.str1') }}</text>
						<text class="amount">{{totalReceivable}}</text>
					</view>
					<view class="stats-row">
						<view class="stat-item">
							<text class="stat-value">{{transactionCount}}</text>
							<text class="stat-title">{{ $t('business.str2') }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-value">{{cashReceivable}}</text>
							<text class="stat-title">{{ $t('business.str3') }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-value">{{cumulativeNewMemberCount}}</text>
							<text class="stat-title">{{ $t('business.str4') }}</text>
						</view>
					</view>
				</view>
				<view v-if="roleProperty==2" class="function">
					<view v-if="routes && routes.includes('ticket_check')" class="function-button"
						style="background-color: #9309A8;" @click="handleButtonClick('ticket_check')">
						{{$t('business.str5')}}
					</view>
					<view v-if="routes && routes.includes('deduct_coin')" class="function-button"
						style="background-color: #E08E02;margin-left: 5px;" @click="handleButtonClick('deduct_coin')">
						{{$t('business.str6')}}
					</view>
					<view v-if="routes && routes.includes('deduct_ticket')" class="function-button"
						style="background-color: #393939;margin-left: 5px;" @click="handleButtonClick('deduct_ticket')">
						{{$t('business.str7')}}
					</view>
					<view v-if="routes && routes.includes('insert_ticket')" class="function-button"
						style="background-color: #D54316;margin-left: 5px;" @click="handleButtonClick('insert_ticket')">
						{{$t('business.str8')}}
					</view>
				</view>

				<!-- 顶部收入统计区域 商盟端 -->
				<view v-if="roleProperty==3" class="header">
					<view class="total-income">
						<text class="title">{{ $t('business.str26') }}</text>
						<text class="amount">{{totalWriteOff}}</text>
					</view>
					<view class="stats-row">
						<view class="stat-item">
							<text class="stat-value">{{totalAmount}}</text>
							<text class="stat-title">{{ $t('business.str27') }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-value">{{totalGameCoin}}</text>
							<text class="stat-title">{{ $t('business.str28') }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-value">{{totalPlyCoin}}</text>
							<text class="stat-title">{{ $t('business.str29') }}</text>
						</view>
					</view>
					<view class="stats-row">
						<view class="stat-item">
							<text class="stat-value">{{totalAmount}}</text>
							<text class="stat-title">{{ $t('business.str32') }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-value">{{totalGameCoin}}</text>
							<text class="stat-title">{{ $t('business.str33') }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-value">{{totalPlyCoin}}</text>
							<text class="stat-title">{{ $t('business.str34') }}</text>
						</view>
					</view>
				</view>

				<!-- 动态渲染菜单按钮列表，一行固定3列 -->
				<!-- 权限菜单区域 -->
				<!-- 加载中状态 -->
				<view v-if="isLoadingRoutes" class="loading-container">
					<view class="loading-spinner"></view>
					<view class="loading-text">加载权限中...</view>
				</view>

				<!-- 加载失败状态 -->
				<view v-else-if="routesLoadFailed" class="error-container">
					<view class="error-text">权限加载失败</view>
					<button class="retry-button" @click="retryLoadRoutes">重试</button>
				</view>

				<!-- 权限加载成功且有数据时显示菜单 -->
				<view v-else-if="serviceList.length > 0" class="function-grid">
					<view v-for="(button, index) in serviceList" :key="index" class="item-button"
						@click="handleButtonClick(button.action)">
						<image class="iamge" :src="button.icon"></image>
						<view class="button-title">{{button.text}}</view>
					</view>
				</view>

				<!-- 权限加载成功但无权限时显示 -->
				<view v-else class="empty-container">
					<view class="empty-text">暂无可用功能</view>
				</view>

			</scroll-view>
		</view>
		<!-- 打卡上班弹窗 - 移到根容器顶层确保正确悬浮 -->
		<uni-popup ref="popup" :mask-click="false" mask-bg-color="rgba(0, 0, 0, 0.7)">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">打卡上班</text>
				</view>
				<view class="dialog-content">
					<view class="time-display">
						<text class="time-text">{{currentTime}}</text>
					</view>
					<view class="punch-hint">
						<text>请打卡后开始工作</text>
					</view>
				</view>
				<view class="popup-footer">
					<button class="punch-button" @click="punchIn">打卡上班</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		name: "data-revenue",
		data() {
			return {
				totalReceivable: 0,
				transactionCount: 0,
				cashReceivable: 0,
				cumulativeNewMemberCount: 0,

				totalWriteOff: 150.00,
				totalAmount: 0,
				totalGameCoin: 0,
				totalPlyCoin: 0,

				roleProperty: 0, //1=管理端 2=手机服务端 3=商盟端
				routes: [], // 从接口获取的权限菜单列表
				isLoadingRoutes: true, // 权限加载状态
				routesLoadFailed: false, // 权限加载是否失败
				currentTime: '', // 当前系统时间
				timeInterval: null, // 定时器

			};
		},
		onLoad() {
			// this.initializeLanguage().finally(() => {
				uni.setNavigationBarTitle({
					title: this.$t('tabbar.business')
				});
				uni.setTabBarItem({
					index: 0,
					text: this.$t('tabbar.business')
				});
				uni.setTabBarItem({
					index: 1,
					text: this.$t('tabbar.message')
				});
				uni.setTabBarItem({
					index: 2,
					text: this.$t('tabbar.mine')
				});
			// });
		},
		onShow() {
			uni.setNavigationBarTitle({
				title: this.$t('tabbar.business')
			});

			const shiftVerificationNo = uni.getStorageSync('shiftVerificationNo'); //交班核实编码 用于判断上班
			//如果没有交班合适编码，显示上班弹窗 
			if (!shiftVerificationNo) {
				//1.查询接口是否有交班合适编码
				//2.如果有，存储到本地
				//3.如果没有，显示弹窗提示，弹窗禁止关闭,弹窗显示： 当前系统时间(秒跳动)，打卡上班按钮
				this.checkShiftVerificationNo();
			}

		},
		computed: {
			// 按钮列表数据 - 使用计算属性确保语言切换时自动更新，并且根据接口返回的权限过滤
			serviceList() {
				// 定义完整的菜单列表
				const allServices = [{
						icon: '/static/yucunkuan.png',
						text: this.$t('business.str9'),
						action: 'recharge'
					},
					{
						icon: '/static/menpiao.png',
						text: this.$t('business.str12'),
						action: 'sell_ticket'
					},
					{
						icon: '/static/shangpin.png',
						text: this.$t('business.str13'),
						action: 'product_sales'
					},
					{
						icon: '/static/tuihuo.png',
						text: this.$t('business.str14'),
						action: 'order_record'
					},
					{
						icon: '/static/chongtui.png',
						text: this.$t('business.str15'),
						action: 'free_recharge'
					},
					{
						icon: '/static/members.png',
						text: this.$t('business.str16'),
						action: 'card_activation'
					},
					{
						icon: '/static/members_query.png',
						text: this.$t('business.str17'),
						action: 'vip_query'
					},
					{
						icon: '/static/zhuanhuan.png',
						text: this.$t('business.str35'),
						action: 'transformation'
					},
					{
						icon: '/static/remote_start.png',
						text: this.$t('business.str30'),
						action: 'remote_start'
					},
					{
						icon: '/static/go_off_word.png',
						text: this.$t('business.str25'),
						action: 'off_work'
					}, {
						icon: '/static/koubi.png',
						text: this.$t('business.str22'),
						action: 'write_off'
					},
					{
						icon: '/static/kbjl.png',
						text: this.$t('business.str23'),
						action: 'write_off_record'
					},
					{
						icon: '/static/duizhang.png',
						text: this.$t('business.str24'),
						action: 'reconciliation'
					},
					{
						icon: '/static/dzjl.png',
						text: this.$t('business.str31'),
						action: 'reconciliation_record'
					}
				];

				// 只有在权限加载完成且routes有数据时才返回过滤后的菜单
				if (this.routes && this.routes.length > 0) {
					return allServices.filter(button => this.routes.includes(button.action));
				}

				// 其他情况返回空数组
				return [];
			}
		},
		mounted() {
			this.roleProperty = uni.getStorageSync('roleProperty');
			// 加载用户权限菜单
			this.loadUserRoutes();
			// 加载当班销售数据
			this.loadTopData();
		},
		onPullDownRefresh() {
			console.log('触发下拉刷新');
			// 加载当班销售数据
			this.loadTopData().finally(() => {
				// 所有数据获取完成后，停止下拉刷新动画
				uni.stopPullDownRefresh();
			});
		},
		methods: {
			async initializeLanguage() {
				// 优先从本地存储获取语言设置
				const storedLanguage = uni.getStorageSync('currentLanguage');
				// 如果没有存储的语言，则使用系统语言
				const systemLanguage = uni.getLocale();
				// 设置当前语言，默认使用英语
				this.currentLanguage = storedLanguage || systemLanguage || 'en';
				console.log('初始化语言:', this.currentLanguage);
				// 应用i18n语言设置
				if (this.$i18n) {
					this.$i18n.locale = this.currentLanguage;
				}
			},
			async loadTopData() {
				if (this.roleProperty == 2) {
					// 加载当班销售数据(手机服务员角色)
					this.loadMobileOnDutySalesData();
				} else {
					// 加载当班销售数据(商盟角色)
				}
			},
			// 加载当班销售数据(手机服务员角色)
			async loadMobileOnDutySalesData() {
				const shiftVerificationNo = uni.getStorageSync('shiftVerificationNo'); //交班核实编码 用于判断上班
				//如果没有交班合适编码，显示上班弹窗 
				if (!shiftVerificationNo) {
					console.log('没有交班合适编码，不能查询当班销售数据');
					return;
				}
				try {
					// 发送POST请求调用接口
					const response = await this.$http.post('/shiftVerification/getMobileOnDutySalesData', {
						shiftVerificationNo: shiftVerificationNo,
					});
					// 处理接口返回结果
					if (response) {
						this.totalReceivable = response.totalReceivable;
						this.transactionCount = response.transactionCount;
						this.cashReceivable = response.cashReceivable;
						this.cumulativeNewMemberCount = response.cumulativeNewMemberCount;
					} else {
						console.log('查询当班销售数据失败:', response);
						uni.showToast({
							title: '查询当班销售数据失败：' + response,
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('查询当班销售数据失败:', error);
				}
			},
			// 检查是否有未下班的打卡记录
			async checkShiftVerificationNo() {
				try {
					// 发送POST请求调用接口
					const response = await this.$http.post('/shiftVerification/getNotOffDutyPunchRecords', {
						mac: '',
						businessTerminalType: 'mobileService'
					});

					// 处理接口返回结果
					if (response) {
						// 如果有数据，存储到本地
						uni.setStorageSync('shiftVerificationNo', response);
					} else {
						// 如果没有数据，显示打卡弹窗
						// 更新时间相关操作无论弹窗是否成功都执行
						this.$refs.popup.open();
						this.updateCurrentTime();
						this.startTimeInterval();
					}
				} catch (error) {
					console.error('查询未下班打卡记录失败:', error);
					// 错误情况下也显示打卡弹窗
					// 更新时间相关操作无论弹窗是否成功都执行
					this.$refs.popup.open();
					this.updateCurrentTime();
					this.startTimeInterval();
				}
			},

			// 更新当前时间
			updateCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},

			// 开始时间定时器
			startTimeInterval() {
				// 清除已存在的定时器
				if (this.timeInterval) {
					clearInterval(this.timeInterval);
				}
				// 设置新的定时器，每秒更新一次时间
				this.timeInterval = setInterval(() => {
					this.updateCurrentTime();
				}, 1000);
			},

			// 停止时间定时器
			stopTimeInterval() {
				if (this.timeInterval) {
					clearInterval(this.timeInterval);
					this.timeInterval = null;
				}
			},

			// 打卡上班
			async punchIn() {
				try {
					const response = await this.$http.post('/shiftVerification/punchIn', {
						businessTerminalType: 'mobileService',
						shiftStart: this.currentTime
					});
					// 检查响应数据
					if (response) {
						uni.setStorageSync('shiftVerificationNo', response); //缓存编码
						uni.showToast({
							title: '打卡上班成功',
							icon: 'success'
						});
						this.$refs.popup.close();
						this.startTimeInterval()
					} else {
						uni.showToast({
							title: '打卡上班失败',
							icon: 'fail'
						});
					}
				} catch (error) {
					console.error('打卡上班失败:', error);
					uni.showToast({
						title: '打卡上班失败',
						icon: 'fail'
					});
				}
			},

			// 加载用户权限菜单
			async loadUserRoutes() {
				// 设置加载状态
				this.isLoadingRoutes = true;
				this.routesLoadFailed = false;

				try {
					// 调用接口获取权限菜单列表
					const response = await this.$http.post('/auth/get/user/routes', {
						businessTerminalType: 'mobileService'
					});

					// 检查响应数据
					if (response && response.routes) {
						try {
							// 解析routes JSON字符串为数组
							this.routes = JSON.parse(response.routes);
							console.log('解析后的权限菜单列表:', this.routes);
							this.routesLoadFailed = false;
						} catch (parseError) {
							console.error('解析routes数据失败:', parseError);
							this.routes = [];
							this.routesLoadFailed = true;
						}
					} else {
						console.warn('接口未返回routes数据');
						this.routes = [];
						this.routesLoadFailed = true;
					}
				} catch (error) {
					console.error('获取用户权限菜单失败:', error);
					this.routes = [];
					this.routesLoadFailed = true;
				} finally {
					// 无论成功失败，都设置加载完成
					this.isLoadingRoutes = false;
				}
			},

			// 重试加载权限菜单
			retryLoadRoutes() {
				this.loadUserRoutes();
			},
			// 动态调用对应方法
			handleButtonClick(action) {
				switch (action) {
					case 'ticket_check':
						uni.navigateTo({
							url: '/pages/home/check-ticket'
						});
						break;
					case 'deduct_coin':
						uni.navigateTo({
							url: '/pages/home/coin-deduction'
						});
						break;
					case 'deduct_ticket':
						uni.navigateTo({
							url: '/pages/home/ticket-deduction'
						});
						break;
					case 'insert_ticket':
						uni.navigateTo({
							url: '/pages/home/ticket-deposit'
						});
						break;
					case 'recharge':
						uni.navigateTo({
							url: '/pages/recharge/recharge-list'
						});
						break;
					case 'sell_ticket':
						uni.navigateTo({
							url: '/pages/ticket/ticket-list'
						});
						break;
					case 'product_sales':
						uni.navigateTo({
							url: '/pages/goods/retail-goods'
						});
						break;
					case 'order_record':
						uni.navigateTo({
							url: '/pages/order/order-list'
						});
						break;
					case 'free_recharge':
						uni.navigateTo({
							url: '/pages/recharge/free-recharge-home'
						});
						break;
					case 'card_activation':
						uni.navigateTo({
							url: '/pages/member/member-card-register'
						});
						break;
					case 'vip_query':
						uni.navigateTo({
							url: '/pages/member/member-query'
						});
						break;
					case 'transformation':
						uni.navigateTo({
							url: '/pages/home/transformation'
						});
						break;
					case 'remote_start':
						uni.navigateTo({
							url: '/pages/remote-start/remote-start'
						});
						break;
					case 'off_work':
						//打卡下班
						uni.navigateTo({
							url: '/pages/home/off-word'
						});
						break;
					case 'write_off':
						uni.navigateTo({
							url: '/pages/shangmeng/shangmeng-coin-deduction'
						});
						break;
					case 'write_off_record':
						uni.navigateTo({
							url: '/pages/shangmeng/shangmeng-coin-deduction-record'
						});
						break;
					case 'reconciliation':
						uni.navigateTo({
							url: '/pages/shangmeng/shangmeng-checkout'
						});
						break;
					case 'reconciliation_record':
						uni.navigateTo({
							url: '/pages/shangmeng/shangmeng-checkout-record'
						});
						break
				}
			}
		},
		// 组件卸载时清除定时器
		beforeUnmount() {
			this.stopTimeInterval();
		}
	}
</script>

<style lang="scss">
	.content {
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: start;
		align-items: center;
		padding: 15rpx;
	}

	/* uni-popup相关样式 */
	.popup-content {
		width: 100%;
		background-color: #ffffff;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.popup-header {
		padding: 30rpx;
		text-align: center;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.popup-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
	}

	.popup-footer {
		padding: 30rpx;
		text-align: center;
	}

	.scroll-Y {
		flex: 1;
		min-height: 0;
		/*避免内容溢出*/
		padding-bottom: 20rpx;
		width: 100%;
	}

	/* 顶部区域样式 */
	.header {
		background-image: linear-gradient(120deg, #FF2916 0%, #FF542E 100%);
		width: 100%;
		height: fit-content;
		border-radius: 15rpx;
		padding-top: 30rpx;
		padding-bottom: 30rpx;
	}

	.total-income {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.title {
		font-size: 28rpx;
		color: #fff;
	}

	.amount {
		font-size: 48rpx;
		font-weight: bold;
		color: #fff;
		margin-top: 10rpx;
	}

	.stats-row {
		display: flex;
		justify-content: space-around;
		margin-top: 30rpx;
	}

	.stat-item {
		display: flex;
		flex: 1;
		flex-direction: column;
		align-items: center;
	}

	.stat-title {
		font-size: 24rpx;
		color: #fff;
	}

	.stat-value {
		font-size: 32rpx;
		color: #fff;
		font-weight: bold;
		margin-top: 5rpx;
	}

	.function {
		display: flex;
		justify-content: center;
		align-items: center;

		.function-button {
			display: flex;
			flex: 1;
			color: white;
			min-height: 80rpx;
			// height: fit-content;
			margin-top: 20rpx;
			border-radius: 5rpx;
			justify-content: center;
			align-items: center;
			text-align: center;
			line-height: 20px;
		}
	}

	.function-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		/* 一行固定3列 */
		grid-gap: 1px;
		/* 设置网格间距 */
		margin-top: 20rpx;
		width: 100%;
	}

	/* 加载中样式 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 6rpx solid #f3f3f3;
		border-top: 6rpx solid #FF542E;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		color: #666;
		font-size: 28rpx;
	}

	/* 加载失败样式 */
	.error-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60rpx 0;
	}

	.error-text {
		color: #ff4d4f;
		font-size: 32rpx;
		margin-bottom: 30rpx;
	}

	.retry-button {
		background-color: #FF542E;
		color: white;
		border: none;
		padding: 0 60rpx;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border-radius: 40rpx;
	}

	.retry-button:active {
		background-color: #E04825;
	}

	/* 无权限样式 */
	.empty-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 80rpx 0;
	}

	.empty-text {
		color: #999;
		font-size: 28rpx;
	}

	.iamge {
		width: 68rpx;
		height: 68rpx;
		flex-shrink: 0;
		/* 防止图片被压缩 */
	}

	.item-button {
		width: 100%;
		height: 190rpx;
		/* 固定高度 */
		background-color: white;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
	}

	.button-title {
		font-size: 28rpx;
		font-weight: 500;
		margin-top: 15rpx;
		text-align: center;
		/* 文本居中 */
		word-break: break-word;
		/* 允许换行 */
		padding: 0 10rpx;
		width: 100%;
		/* 确保宽度一致 */
		height: auto;
		/* 高度自适应 */
		max-height: 60rpx;
		/* 限制最大高度，防止文本过长导致样式错乱 */
		overflow: hidden;
		/* 超出部分隐藏 */
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		/* 最多显示两行 */
	}

	/* 打卡弹窗样式 */
	.dialog-content {
		padding: 40rpx 30rpx;
		text-align: center;
		background-color: #ffffff;
	}

	.time-display {
		margin-bottom: 30rpx;
	}

	.time-text {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		letter-spacing: 2rpx;
	}

	.punch-hint {
		font-size: 28rpx;
		color: #666666;
		margin-bottom: 20rpx;
	}

	.punch-button {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		background-color: #FF542E;
		color: #ffffff;
		font-size: 32rpx;
		border-radius: 45rpx;
		border: none;
	}

	.punch-button:active {
		background-color: #E04825;
	}
</style>